package com.fauks.ndk.player

import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView

/**
 * <pre>
 *     author : slx
 *     time   : 2021/06/30
 *     desc   :
 * </pre>
 */
class EasyPlayer : SurfaceHolder.Callback {

    private var dataSource: String = ""
    private lateinit var surfaceHolder: SurfaceHolder

    private var onPrepareListener: (() -> Unit)? = null


    // 设置播放源:播放文件、直播地址
    fun setDataSource(dataSource: String) {
        this.dataSource = dataSource
    }

    // 设置播放的画布
    fun setSurfaceView(surfaceView: SurfaceView) {
        surfaceHolder = surfaceView.holder
        surfaceHolder.addCallback(this)
    }

    // 准备、播放、暂停、停止、释放资源等方法
    fun prepare() {
        nativePrepare(dataSource)
    }

    fun start() {}
    fun stop() {}
    fun release() {
        surfaceHolder.removeCallback(this)
    }

    // C++反射回调的方法
    fun onError(errorCode: Int) {
        Log.i("fauks", "ffmpeg errorCode = $errorCode")
    }

    fun onPrepare() {
        onPrepareListener?.invoke()
    }

    // 画布创建完毕
    override fun surfaceCreated(holder: SurfaceHolder) {
    }

    // 画布发生改变时回调：横竖屏切换、按下Home键
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
    }

    // 销毁画布：退出应用、按下Home键
    override fun surfaceDestroyed(holder: SurfaceHolder) {
    }

    // 获取ffmpeg的版本号
    external fun getVersionInfo(): String

    // 调用native方法准备播放源
    external fun nativePrepare(dataSource: String)

    fun setOnPrepareListener(listener: () -> Unit) {
        this.onPrepareListener = listener
    }

    companion object {
        init {
            System.loadLibrary("ndk-test")
        }
    }
}